import {
  http,
  HttpResponse,
  type DefaultBodyType,
  type StrictRequest
} from 'msw'
import type { User } from '@/types/domain/entity/User'

// 初始用户数据
const mockUsers: User[] = [
  {
    userId: 1,
    avatar: 'https://wpimg.wal1stcn.com/f7787380',
    username: 'admin',
    password: '111111',
    desc: '平台管理员',
    roles: ['平台管理员'],
    buttons: ['cuser.detail', 'cuser.edit'],
    routes: ['home', 'dashboard'],
    token: 'Admin Token'
  },
  {
    userId: 2,
    avatar: 'https://wpimg.wal1stcn.com/f7787381',
    username: 'editor',
    password: '222222',
    desc: '内容编辑员',
    roles: ['内容管理员'],
    buttons: ['article.create', 'article.edit'],
    routes: ['home', 'article'],
    token: 'Editor Token'
  },
  {
    userId: 3,
    avatar: 'https://wpimg.wal1stcn.com/f7787382',
    username: 'guest',
    password: '333333',
    desc: '访客用户',
    roles: ['访客'],
    buttons: [],
    routes: ['home'],
    token: 'Guest Token'
  },
  {
    userId: 4,
    avatar: 'https://wpimg.wal1stcn.com/f7787383',
    username: 'dev',
    password: '444444',
    desc: '开发人员',
    roles: ['开发者'],
    buttons: ['code.view', 'code.push'],
    routes: ['home', 'devtools'],
    token: 'Dev Token'
  }
]

// 用户状态管理
let currentUsers = [...mockUsers]
let nextUserId = 5

// 验证token的辅助函数
const validateToken = (request: StrictRequest<DefaultBodyType>) => {
  const authHeader = request.headers.get('Authorization') || ''
  const token = authHeader.replace(/^Bearer\s+/i, '')
  if (!token) {
    return { isValid: false, user: null, error: 'Unauthorized' }
  }
  const user = currentUsers.find(u => u.token === token)
  if (!user) {
    return { isValid: false, user: null, error: 'Forbidden,no such permission' }
  }
  return { isValid: true, user, error: null }
}

export const userHandlers = [
  // 获取用户信息
  http.get('/api/user/info', async ({ request }) => {
    const { isValid, user, error } = validateToken(request)
    if (!isValid) {
      return HttpResponse.json(
        { message: error },
        {
          status: error === 'Unauthorized' ? 401 : 403
        }
      )
    }
    // 返回用户信息时排除密码
    const { password, ...userInfo } = user!
    void password // 明确忽略密码字段
    return HttpResponse.json(userInfo)
  }),

  // 用户登录
  http.post('/api/user/login', async ({ request }) => {
    const body = await request.json()
    const { username, password } = body as {
      username: string
      password: string
    }

    if (!username || !password) {
      return HttpResponse.json(
        { message: '用户名和密码不能为空' },
        { status: 400 }
      )
    }

    const user = currentUsers.find(
      u => u.username === username && u.password === password
    )

    if (user) {
      return HttpResponse.json({
        token: user.token,
        expiresIn: 3600,
        user: {
          userId: user.userId,
          username: user.username,
          avatar: user.avatar,
          desc: user.desc,
          roles: user.roles
        }
      })
    }

    return HttpResponse.json({ message: '用户名或密码错误' }, { status: 401 })
  }),

  // 用户登出
  http.post('/api/user/logout', async ({ request }) => {
    const { isValid } = validateToken(request)
    if (!isValid) {
      return HttpResponse.json({ message: 'Unauthorized' }, { status: 401 })
    }
    return HttpResponse.json({ message: '登出成功' })
  }),

  // 获取用户列表（分页）
  http.get('/api/user/list', async ({ request }) => {
    const { isValid } = validateToken(request)
    if (!isValid) {
      return HttpResponse.json({ message: 'Unauthorized' }, { status: 401 })
    }

    const url = new URL(request.url)
    const page = parseInt(url.searchParams.get('page') || '1')
    const pageSize = parseInt(url.searchParams.get('pageSize') || '10')
    const keyword = url.searchParams.get('keyword') || ''

    let filteredUsers = currentUsers
    if (keyword) {
      filteredUsers = currentUsers.filter(
        user =>
          user.username.includes(keyword) ||
          user.desc.includes(keyword) ||
          user.roles.some(role => role.includes(keyword))
      )
    }

    const total = filteredUsers.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const users = filteredUsers
      .slice(start, end)
      .map(({ password, ...user }) => {
        void password // 明确忽略密码字段
        return user
      })

    return HttpResponse.json({
      users,
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize)
    })
  }),

  // 创建用户
  http.post('/api/user/create', async ({ request }) => {
    const { isValid } = validateToken(request)
    if (!isValid) {
      return HttpResponse.json({ message: 'Unauthorized' }, { status: 401 })
    }

    const body = await request.json()
    const {
      username,
      password: newPassword,
      desc,
      roles,
      buttons,
      routes
    } = body as Partial<User>

    if (!username || !newPassword) {
      return HttpResponse.json(
        { message: '用户名和密码不能为空' },
        { status: 400 }
      )
    }

    // 检查用户名是否已存在
    if (currentUsers.some(u => u.username === username)) {
      return HttpResponse.json({ message: '用户名已存在' }, { status: 400 })
    }

    const newUser: User = {
      userId: nextUserId++,
      username,
      password: newPassword,
      desc: desc || '',
      roles: roles || ['访客'],
      buttons: buttons || [],
      routes: routes || ['home'],
      token: `${username} Token ${Date.now()}`,
      avatar: `https://wpimg.wal1stcn.com/f778738${nextUserId}`
    }

    currentUsers.push(newUser)
    const { password, ...userInfo } = newUser
    void password // 明确忽略密码字段
    return HttpResponse.json({ message: '用户创建成功', user: userInfo })
  }),

  // 更新用户信息
  http.put('/api/user/:id', async ({ request, params }) => {
    const { isValid } = validateToken(request)
    if (!isValid) {
      return HttpResponse.json({ message: 'Unauthorized' }, { status: 401 })
    }

    const userId = parseInt(params.id as string)
    const body = await request.json()
    const userIndex = currentUsers.findIndex(u => u.userId === userId)

    if (userIndex === -1) {
      return HttpResponse.json({ message: '用户不存在' }, { status: 404 })
    }

    // 更新用户信息（保留token和userId）
    const currentUser = currentUsers[userIndex]!
    const updatedUser: User = {
      ...currentUser,
      ...(body as Partial<User>),
      userId,
      token: currentUser.token
    }

    currentUsers[userIndex] = updatedUser
    const { password, ...userInfo } = updatedUser
    void password // 明确忽略密码字段
    return HttpResponse.json({ message: '用户信息更新成功', user: userInfo })
  }),

  // 删除用户
  http.delete('/api/user/:id', async ({ request, params }) => {
    const { isValid } = validateToken(request)
    if (!isValid) {
      return HttpResponse.json({ message: 'Unauthorized' }, { status: 401 })
    }

    const userId = parseInt(params.id as string)
    const userIndex = currentUsers.findIndex(u => u.userId === userId)

    if (userIndex === -1) {
      return HttpResponse.json({ message: '用户不存在' }, { status: 404 })
    }

    // 不能删除自己
    const currentUser = currentUsers[userIndex]!
    const authToken = request.headers
      .get('Authorization')
      ?.replace(/^Bearer\s+/i, '')
    if (currentUser.token === authToken) {
      return HttpResponse.json({ message: '不能删除自己' }, { status: 400 })
    }

    currentUsers.splice(userIndex, 1)
    return HttpResponse.json({ message: '用户删除成功' })
  }),

  // 修改密码
  http.put('/api/user/change-password', async ({ request }) => {
    const { isValid, user } = validateToken(request)
    if (!isValid) {
      return HttpResponse.json({ message: 'Unauthorized' }, { status: 401 })
    }

    const body = await request.json()
    const { oldPassword, newPassword } = body as {
      oldPassword: string
      newPassword: string
    }

    if (!oldPassword || !newPassword) {
      return HttpResponse.json(
        { message: '旧密码和新密码不能为空' },
        { status: 400 }
      )
    }

    if (user!.password !== oldPassword) {
      return HttpResponse.json({ message: '旧密码错误' }, { status: 400 })
    }

    const userIndex = currentUsers.findIndex(u => u.userId === user!.userId)
    if (userIndex !== -1) {
      currentUsers[userIndex]!.password = newPassword
    }

    return HttpResponse.json({ message: '密码修改成功' })
  }),

  // 获取用户统计信息
  http.get('/api/user/stats', async ({ request }) => {
    const { isValid } = validateToken(request)
    if (!isValid) {
      return HttpResponse.json({ message: 'Unauthorized' }, { status: 401 })
    }

    const totalUsers = currentUsers.length
    const roleStats = currentUsers.reduce(
      (acc, user) => {
        user.roles.forEach(role => {
          acc[role] = (acc[role] || 0) + 1
        })
        return acc
      },
      {} as Record<string, number>
    )

    return HttpResponse.json({
      totalUsers,
      roleStats,
      onlineUsers: Math.floor(Math.random() * totalUsers) + 1 // 模拟在线用户数
    })
  })
]
